home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / nevow / livepage.py < prev    next >
Text File  |  2006-03-08  |  30KB  |  902 lines

  1. # -*- test-case-name: nevow.test.test_livepage -*-
  2.  
  3. # Copyright (c) 2004 Divmod.
  4. # See LICENSE for details.
  5.  
  6. """Provides a bidirectional channel for sending out-of-band
  7. events between client and server without refreshing the whole
  8. page.
  9. """
  10. import itertools, types
  11. import warnings
  12.  
  13. from zope.interface import implements, Interface
  14.  
  15. from twisted.internet import defer, error
  16. from twisted.internet.task import LoopingCall
  17. from twisted.python import log
  18.  
  19. from nevow import tags, inevow, context, static, flat, rend, url, util, stan
  20.  
  21. # If you need to debug livepage itself or your livepage app, set this to true
  22. DEBUG = False
  23.  
  24. _jslog = None
  25.  
  26. def _openjslog():
  27.     global _jslog
  28.     if _jslog is None:
  29.         _jslog = file("js.log", "w")
  30.         _jslog.write("**********\n")
  31.         _jslog.flush()
  32.     return _jslog
  33.  
  34. def jslog(*x):
  35.     if DEBUG:
  36.         mylog = _openjslog()
  37.         for y in x:
  38.             mylog.write(str(y))
  39.         mylog.flush()
  40.  
  41. class JavascriptContext(context.WovenContext):
  42.     def __init__(self, parent=None, tag=None, isAttrib=None,
  43.                 inJSSingleQuoteString=None, remembrances=None):
  44.         super(JavascriptContext, self).__init__(
  45.             parent, tag, inJS=True, isAttrib=isAttrib,
  46.             inJSSingleQuoteString=inJSSingleQuoteString,
  47.             remembrances=None)
  48.  
  49.  
  50. class TimeoutException(Exception):
  51.     pass
  52.  
  53.  
  54. class ClientSideException(Exception):
  55.     pass
  56.  
  57.  
  58. class SingleQuote(object):
  59.     def __init__(self, children):
  60.         self.children = children
  61.  
  62.     def __repr__(self):
  63.         return "%s(%s)" % (type(self).__name__, self.children)
  64.  
  65.  
  66. def flattenSingleQuote(singleQuote, ctx):
  67.     new = JavascriptContext(ctx, tags.invisible[singleQuote], inJSSingleQuoteString=True)
  68.     return flat.serialize(singleQuote.children, new)
  69. flat.registerFlattener(flattenSingleQuote, SingleQuote)
  70.  
  71.  
  72. class _js(object):
  73.     """Stan for Javascript. There is a convenience instance of this
  74.     class named "js" in the livepage module which you should use
  75.     instead of the _js class directly.
  76.  
  77.     Marker indicating literal Javascript should be rendered.
  78.     No escaping will be performed.
  79.  
  80.     When inside a JavascriptContext, Nevow will automatically put
  81.     apostrophe quote marks around any Python strings it renders.
  82.     This makes turning a Python string into a JavaScript string very
  83.     easy. However, there are often situations where you wish to
  84.     generate some literal Javascript code and do not wish quote
  85.     marks to be placed around it. In this situation, the js object
  86.     should be used.
  87.  
  88.     The simplest usage is to simply pass a python string to js.
  89.     When the js object is rendered, the python string will be
  90.     rendered as if it were literal javascript. For example:
  91.  
  92.         client.send(js(\"alert('hello')\"))
  93.  
  94.     However, to make the generation of Javascript more
  95.     convenient, the js object also provides safe implementations
  96.     of __getattr__, __call__, and __getitem__. See the following
  97.     examples to get an idea of how to use it. The Python code
  98.     is to the left of the -> and the Javascript which results is
  99.     to the right.
  100.  
  101.         js(\"alert('any javascript you like')\") -> alert('any javascript you like')
  102.  
  103.         js.window.title -> window.title
  104.  
  105.         js.document.getElementById('foo') -> document.getElementById('foo')
  106.  
  107.         js.myFunction('my argument') -> myFunction('my argument')
  108.  
  109.         js.myFunction(True, 5, \"it's a beautiful day\") -> myFunction(true, 5, 'it\\'s a beautiful day')
  110.  
  111.         js.document.all[\"something\"] -> document.all['something']
  112.  
  113.         js[1, 2] -> [1, 2]
  114.  
  115.     XXX TODO support javascript object literals somehow? (They look like dicts)
  116.     perhaps like this:
  117.  
  118.         js[\"one\": 1, \"two\": 2] -> {\"one\": 1, \"two\": 2}
  119.  
  120.     The livepage module includes many convenient instances of the js object.
  121.     It includes the literals:
  122.  
  123.         document
  124.         window
  125.         this
  126.         self
  127.  
  128.     It includes shorthand for commonly called javascript functions:
  129.  
  130.         alert -> alert
  131.         get -> document.getElementById
  132.         set -> nevow_setNode
  133.         append -> nevow_appendNode
  134.         prepend -> nevow.prependNode
  135.         insert -> nevow.insertNode
  136.  
  137.     It includes convenience calls against the client-side server object:
  138.  
  139.         server.handle('callMe') -> server.handle('callMe')
  140.  
  141.     It includes commonly-used fragments of javascript:
  142.  
  143.         stop -> ; return false;
  144.         eol -> \\n
  145.  
  146.     Stop is used to prevent the browser from executing it's default
  147.     event handler. For example:
  148.  
  149.         button(onclick=[server.handle('click'), stop]) -> <button onclick=\"server.handle('click'); return false;\" />
  150.  
  151.     EOL is currently required to separate statements (this requirement
  152.     may go away in the future). For example:
  153.  
  154.         client.send([
  155.             alert('hello'), eol,
  156.             alert('goodbye')])
  157.  
  158.     XXX TODO: investigate whether rendering a \n between list elements
  159.     in a JavascriptContext has any ill effects.
  160.     """
  161.  
  162.     def __init__(self, name=None):
  163.         if name is None:
  164.             name = []
  165.         if isinstance(name, str):
  166.             name = [stan.raw(name)]
  167.         self._children = name
  168.  
  169.     def __getattr__(self, name):
  170.         if name == 'clone':
  171.             raise RuntimeError("Can't clone")
  172.         if self._children:
  173.             newchildren = self._children[:]
  174.             newchildren.append(stan.raw('.'+name))
  175.             return self.__class__(newchildren)
  176.         return self.__class__(name)
  177.  
  178.     def __call__(self, *args):
  179.         if not self._children:
  180.             return self.__class__(args[0])
  181.         newchildren = self._children[:]
  182.         stuff = []
  183.         for x in args:
  184.             if isinstance(x, (
  185.                 basestring, stan.Tag, types.FunctionType,
  186.                 types.MethodType, types.UnboundMethodType)):
  187.                 x = stan.raw("'"), SingleQuote(x), stan.raw("'")
  188.             stuff.append((x, stan.raw(',')))
  189.         if stuff:
  190.             stuff[-1] = stuff[-1][0]
  191.         newchildren.extend([stan.raw('('), stuff, stan.raw(')')])
  192.         return self.__class__(newchildren)
  193.  
  194.     def __getitem__(self, args):
  195.         if not isinstance(args, (tuple, list)):
  196.             args = (args,)
  197.         newchildren = self._children[:]
  198.         stuff = [(x, stan.raw(',')) for x in args]
  199.         if stuff:
  200.             stuff[-1] = stuff[-1][0]
  201.         newchildren.extend([stan.raw("["), stuff, stan.raw("]")])
  202.         return self.__class__(newchildren)
  203.  
  204.     def __iter__(self):
  205.         """Prevent an infinite loop if someone tries to do
  206.         for x in jsinstance:
  207.         """
  208.         raise NotImplementedError, "js instances are not iterable. (%r)" % (self, )
  209.  
  210.     def __repr__(self):
  211.         return "%s(%r)" % (type(self).__name__, self._children)
  212. def flattenJS(theJS, ctx):
  213.     new = JavascriptContext(ctx, tags.invisible[theJS])
  214.     return flat.serialize(theJS._children, new)
  215. flat.registerFlattener(flattenJS, _js)
  216.  
  217.  
  218. js = _js()
  219. document = _js('document')
  220. get = document.getElementById
  221. window = _js('window')
  222. this = _js('this')
  223. self = _js('self')
  224. server = _js('server')
  225. alert = _js('alert')
  226. stop = _js('; return false;')
  227. eol = tags.raw('\n')
  228.  
  229. set = js.nevow_setNode
  230. append = js.nevow_appendNode
  231. prepend = js.nevow_prependNode
  232. insert = js.nevow_insertNode
  233.  
  234.  
  235. def assign(where, what):
  236.     """Assign what to where. Equivalent to
  237.     where = what;
  238.     """
  239.     return _js([where, stan.raw(" = "), what])
  240.  
  241.  
  242. setq = assign # hee
  243.  
  244.  
  245. def var(where, what):
  246.     """Define local variable 'where' and assign 'what' to it.
  247.     Equivalent to var where = what;
  248.     """
  249.     return _js([stan.raw("var "), where, stan.raw(" = "), what, stan.raw(";")])
  250.  
  251.  
  252. def anonymous(block):
  253.     """Turn block (any stan) into an anonymous JavaScript function
  254.     which takes no arguments. Equivalent to
  255.  
  256.     function () {
  257.         block
  258.     }
  259.     """
  260.     return _js([stan.raw("function() {\n"), block, stan.raw("\n}")])
  261.  
  262.  
  263. class IClientHandle(Interface):
  264.     def hookupOutput(output, finisher=None):
  265.         """hook up an output conduit to this live evil instance.
  266.         """
  267.  
  268.     def send(script):
  269.         """send a script through the output conduit to the browser.
  270.         If no output conduit is yet hooked up, buffer the script
  271.         until one is.
  272.         """
  273.  
  274.     def handleInput(identifier, *args):
  275.         """route some input from the browser to the appropriate
  276.         destination.
  277.         """
  278.  
  279.  
  280. class IHandlerFactory(Interface):
  281.     def locateHandler(ctx, name):
  282.         """Locate a handler callable with the given name.
  283.         """
  284.  
  285.  
  286. class _transient(object):
  287.     def __init__(self, transientId, arguments=None):
  288.         self.transientId = transientId
  289.         if arguments is None:
  290.             arguments = []
  291.         elif isinstance(arguments, tuple):
  292.             arguments = list(arguments)
  293.         else:
  294.             raise TypeError, "Arguments must be None or tuple"
  295.         self.arguments = arguments
  296.  
  297.     def __call__(self, *arguments):
  298.         return type(self)(self.transientId, arguments)
  299.  
  300.  
  301. def flattenTransient(transient, ctx):
  302.     thing = js.server.handle("--transient.%s" % (transient.transientId, ), *transient.arguments)
  303.     return flat.serialize(thing, ctx)
  304. flat.registerFlattener(flattenTransient, _transient)
  305.  
  306.  
  307. class ClientHandle(object):
  308.     """An object which represents the client-side webbrowser.
  309.     """
  310.     implements(IClientHandle)
  311.  
  312.     outputConduit = None
  313.  
  314.     def __init__(self, livePage, handleId, refreshInterval, targetTimeoutCount):
  315.         self.refreshInterval = refreshInterval
  316.         self.targetTimeoutCount = targetTimeoutCount
  317.         self.timeoutCount = 0
  318.         self.livePage = livePage
  319.         self.handleId = handleId
  320.         self.outputBuffer = []
  321.         self.bufferDeferreds = []
  322.         self.closed = False
  323.         self.closeNotifications = []
  324.         self.firstTime = True
  325.         self.timeoutLoop = LoopingCall(self.checkTimeout)
  326.         if refreshInterval:
  327.             self.timeoutLoop.start(self.refreshInterval)
  328.         self._transients = {}
  329.         self.transientCounter = itertools.count().next
  330.         self.nextId = itertools.count().next ## For backwards compatibility with handler
  331.  
  332.     def transient(self, what, *args):
  333.         """Register a transient event handler, 'what'.
  334.         The callable 'what' can only be invoked by the
  335.         client once before being garbage collected.
  336.         Additional attempts to invoke the handler
  337.         will fail.
  338.         """
  339.         transientId = str(self.transientCounter())
  340.         self._transients[transientId] = what
  341.         return _transient(transientId, args)
  342.  
  343.     def popTransient(self, transientId):
  344.         """Remove a transient previously registered
  345.         by a call to transient. Normally, this will be done
  346.         automatically when the transient is invoked.
  347.         However, you can invoke it yourself if you wish
  348.         to revoke the client's capability to call the
  349.         transient handler.
  350.         """
  351.         if DEBUG: print "TRANSIENTS", self._transients
  352.         return self._transients.pop(transientId)
  353.  
  354.     def _actuallySend(self, scripts):
  355.         output = self.outputConduit
  356.         written = []
  357.         def writer(write):
  358.             #print "WRITER", write
  359.             written.append(write)
  360.         def finisher(finish):
  361.             towrite = '\n'.join(written)
  362.             jslog("<<<<<<\n%s\n" % towrite)
  363.             output.callback(towrite)
  364.         flat.flattenFactory(scripts, self.outputContext, writer, finisher)
  365.         self.outputConduit = None
  366.         self.outputContext = None
  367.  
  368.     def send(self, *script):
  369.         """Send the stan "script", which can be flattened to javascript,
  370.         to the browser which is connected to this handle, and evaluate
  371.         it in the context of the browser window.
  372.         """
  373.         if self.outputConduit:
  374.             self._actuallySend(script)
  375.         else:
  376.             self.outputBuffer.append(script)
  377.             self.outputBuffer.append(eol)
  378.  
  379.     def setOutput(self, ctx, output):
  380.         self.timeoutCount = 0
  381.         self.outputContext = ctx
  382.         self.outputConduit = output
  383.         if self.outputBuffer:
  384.             if DEBUG: print "SENDING BUFFERED", self.outputBuffer
  385.             self._actuallySend(self.outputBuffer)
  386.             self.outputBuffer = []
  387.  
  388.     def _actuallyPassed(self, result, deferreds):
  389.         for d in deferreds:
  390.             d.callback(result)
  391.  
  392.     def _actuallyFailed(self, failure, deferreds):
  393.         for d in deferreds:
  394.             d.errback(failure)
  395.  
  396.     def checkTimeout(self):
  397.         if self.outputConduit is not None:
  398.             ## The browser is waiting for us, send a noop.
  399.             self.send(_js('null;'))
  400.             return
  401.         self.timeoutCount += 1
  402.         if self.timeoutCount >= self.targetTimeoutCount:
  403.             ## This connection timed out.
  404.             self._closeComplete(
  405.                 TimeoutException(
  406.                     "This connection did not ACK in at least %s seconds." % (
  407.                         self.targetTimeoutCount * self.refreshInterval, )))
  408.  
  409.     def outputGone(self, failure, output):
  410. #        assert output == self.outputConduit
  411.         # Twisted errbacks with a ConnectionDone when the client closes the
  412.         # connection cleanly. Pretend it didn't happen and carry on.
  413.         self.outputConduit = None
  414.         if failure.check(error.ConnectionDone):
  415.             self._closeComplete()
  416.         else:
  417.             self._closeComplete(failure)
  418.         return None
  419.  
  420.     def _closeComplete(self, failure=None):
  421.         if self.closed:
  422.             return
  423.         self.closed = True
  424.         self.timeoutLoop.stop()
  425.         self.timeoutLoop = None
  426.         for notify in self.closeNotifications[:]:
  427.             if failure is not None:
  428.                 notify.errback(failure)
  429.             else:
  430.                 notify.callback(None)
  431.         self.closeNotifications = []
  432.  
  433.     def notifyOnClose(self):
  434.         """This will return a Deferred that will be fired when the
  435.         connection is closed 'normally', i.e. in response to handle.close()
  436.         . If the connection is lost in any other way (because the browser
  437.         navigated to another page, the browser was shut down, the network
  438.         connection was lost, or the timeout was reached), this will errback
  439.         instead."""
  440.         d = defer.Deferred()
  441.         self.closeNotifications.append(d)
  442.         return d
  443.  
  444.     def close(self, executeScriptBeforeClose=""):
  445.         if DEBUG: print "CLOSE WAS CALLED"
  446.         d = self.notifyOnClose()
  447.         self.send(js.nevow_closeLive(executeScriptBeforeClose))
  448.         return d
  449.  
  450.     def set(self, where, what):
  451.         self.send(js.nevow_setNode(where, what))
  452.  
  453.     def prepend(self, where, what):
  454.         self.send(js.nevow_prependNode(where, what))
  455.  
  456.     def append(self, where, what):
  457.         self.send(js.nevow_appendNode(where, what))
  458.  
  459.     def alert(self, what):
  460.         self.send(js.alert(what))
  461.  
  462.     def call(self, what, *args):
  463.         self.send(js(what)(*args))
  464.  
  465.     def sendScript(self, string):
  466.         warnings.warn(
  467.             "[0.5] nevow.livepage.ClientHandle.sendScript is deprecated, use send instead.",
  468.             DeprecationWarning,
  469.             2)
  470.         self.send(string)
  471.  
  472.  
  473. class DefaultClientHandleFactory(object):
  474.     clientHandleClass = ClientHandle
  475.  
  476.     def __init__(self):
  477.         self.clientHandles = {}
  478.         self.handleCounter = itertools.count().next
  479.  
  480.     def newClientHandle(self, livePage, refreshInterval, targetTimeoutCount):
  481.         handleid = str(self.handleCounter())
  482.         handle = self.clientHandleClass(
  483.             livePage, handleid, refreshInterval, targetTimeoutCount)
  484.         self.clientHandles[handleid] = handle
  485.         handle.notifyOnClose().addBoth(lambda ign: self.deleteHandle(handleid))
  486.         return handle
  487.  
  488.     def deleteHandle(self, handleid):
  489.         del self.clientHandles[handleid]
  490.  
  491.     def getHandleForId(self, handleId):
  492.         """Override this to restore old handles on demand.
  493.         """
  494.         return self.clientHandles[handleId]
  495.  
  496. theDefaultClientHandleFactory = DefaultClientHandleFactory()
  497.  
  498.  
  499. class OutputHandlerResource:
  500.     implements(inevow.IResource)
  501.  
  502.     def __init__(self, clientHandle):
  503.         self.clientHandle = clientHandle
  504.  
  505.     def locateChild(self, ctx, segments):
  506.         raise NotImplementedError()
  507.  
  508.     def renderHTTP(self, ctx):
  509.         request = inevow.IRequest(ctx)
  510.         neverEverCache(request)
  511.         activeChannel(request)
  512.         ctx.remember(jsExceptionHandler, inevow.ICanHandleException)
  513.         request.channel._savedTimeOut = None # XXX TODO
  514.         d = defer.Deferred()
  515.         request.notifyFinish().addErrback(self.clientHandle.outputGone, d)
  516.         jsContext = JavascriptContext(ctx, tags.invisible())
  517.         self.clientHandle.livePage.rememberStuff(jsContext)
  518.         jsContext.remember(self.clientHandle, IClientHandle)
  519.         if self.clientHandle.firstTime:
  520.             self.clientHandle.livePage.goingLive(jsContext, self.clientHandle)
  521.             self.clientHandle.firstTime = False
  522.         self.clientHandle.setOutput(jsContext, d)
  523.         return d
  524.  
  525.  
  526. class InputHandlerResource:
  527.     implements(inevow.IResource)
  528.  
  529.     def __init__(self, clientHandle):
  530.         self.clientHandle = clientHandle
  531.  
  532.     def locateChild(self, ctx, segments):
  533.         raise NotImplementedError()
  534.  
  535.     def renderHTTP(self, ctx):
  536.         self.clientHandle.timeoutCount = 0
  537.  
  538.         request = inevow.IRequest(ctx)
  539.         neverEverCache(request)
  540.         activeChannel(request)
  541.         ctx.remember(self.clientHandle, IClientHandle)
  542.         ctx.remember(jsExceptionHandler, inevow.ICanHandleException)
  543.         self.clientHandle.livePage.rememberStuff(ctx)
  544.  
  545.         handlerName = request.args['handler-name'][0]
  546.         arguments = request.args.get('arguments', ())
  547.         jslog(">>>>>>\n%s %s\n" % (handlerName, arguments))
  548.         if handlerName.startswith('--transient.'):
  549.             handler = self.clientHandle.popTransient(handlerName.split('.')[-1])
  550.         else:
  551.             handler = self.clientHandle.livePage.locateHandler(
  552.                 ctx, request.args['handler-path'],
  553.                 handlerName)
  554.  
  555.         jsContext = JavascriptContext(ctx, tags.invisible[handler])
  556.         towrite = []
  557.  
  558.         def writer(r):
  559.             jslog("WRITE ", r)
  560.             towrite.append(r)
  561.  
  562.         def finisher(r):
  563.             jslog("FINISHED", r)
  564.             writestr = ''.join(towrite)
  565.             jslog("<><><>\n%s\n" % (writestr, ))
  566.             request.write(writestr)
  567.             request.finish()
  568.             return r
  569.  
  570.         result = handler(jsContext, *arguments)
  571.         jslog("RESULT ", result)
  572.  
  573.         if result is None:
  574.             return defer.succeed('')
  575.         return self.clientHandle.livePage.flattenFactory(result, jsContext,
  576.                                             writer, finisher)
  577.  
  578.  
  579.  
  580. class DefaultClientHandlesResource(object):
  581.     implements(inevow.IResource)
  582.  
  583.     clientResources = {
  584.         'input': InputHandlerResource,
  585.         'output': OutputHandlerResource,
  586.         }
  587.  
  588.     clientFactory = theDefaultClientHandleFactory
  589.  
  590.     def locateChild(self, ctx, segments):
  591.         handleId = segments[0]
  592.         handlerType = segments[1]
  593.         client = self.clientFactory.clientHandles[handleId]
  594.  
  595.         return self.clientResources[handlerType](client), segments[2:]
  596.  
  597. theDefaultClientHandlesResource = DefaultClientHandlesResource()
  598.  
  599. class attempt(defer.Deferred):
  600.     """Attempt to do 'stuff' in the browser. callback on the server
  601.     if 'stuff' executes without raising an exception. errback on the
  602.     server if 'stuff' raises a JavaScript exception in the client.
  603.  
  604.     Used like this:
  605.  
  606.     def printIt(what):
  607.         print "Woo!", what
  608.  
  609.     C = IClientHandle(ctx)
  610.     C.send(
  611.         attempt(js("1+1")).addCallback(printIt))
  612.  
  613.     C.send(
  614.         attempt(js("thisWillFail")).addErrback(printIt))
  615.     """
  616.     def __init__(self, stuff):
  617.         self.stuff = stuff
  618.         defer.Deferred.__init__(self)
  619.  
  620.  
  621. def flattenAttemptDeferred(d, ctx):
  622.     def attemptComplete(ctx, result, reason=None):
  623.         if result == 'success':
  624.             d.callback(None)
  625.         else:
  626.             d.errback(ClientSideException(reason))
  627.     transient = IClientHandle(ctx).transient(attemptComplete)
  628.     return flat.serialize([
  629. _js("""try {
  630.     """),
  631.     d.stuff,
  632. _js("""
  633.     """),
  634.     transient('success'),
  635. _js("""
  636. } catch (e) {
  637.     """),
  638.     transient('failure', js.e),
  639. _js("}")
  640.         ], ctx)
  641. flat.registerFlattener(flattenAttemptDeferred, attempt)
  642.  
  643.  
  644. class IOutputEvent(Interface):
  645.     pass
  646.  
  647. class IInputEvent(Interface):
  648.     pass
  649.  
  650.  
  651. class ExceptionHandler(object):
  652.     def renderHTTP_exception(self, ctx, failure):
  653.         log.msg("Exception during input event:")
  654.         log.err(failure)
  655.         request = inevow.IRequest(ctx)
  656.         request.write("throw new Error('Server side error: %s')" % (failure.getErrorMessage().replace("'", "\\'").replace("\n", "\\\n"), ))
  657.         request.finish()
  658.  
  659.     def renderInlineException(self, ctx, reason):
  660.         """TODO: I don't even think renderInlineException is ever called by anybody
  661.         """
  662.         pass
  663.  
  664.  
  665. jsExceptionHandler = ExceptionHandler()
  666.  
  667.  
  668. def neverEverCache(request):
  669.     """ Set headers to indicate that the response to this request should never,
  670.     ever be cached.
  671.     """
  672.     request.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
  673.     request.setHeader('Pragma', 'no-cache')
  674.  
  675. def activeChannel(request):
  676.     """Mark this connection as a 'live' channel by setting the Connection: close
  677.     header and flushing all headers immediately.
  678.     """
  679.     request.setHeader("Connection", "close")
  680.     request.write('')
  681.  
  682. class LivePage(rend.Page):
  683.     """A Page which is Live provides asynchronous, bidirectional RPC between
  684.     Python on the server and JavaScript in the client browser. A LivePage must
  685.     include the "liveglue" JavaScript which includes a unique identifier which
  686.     is assigned to every page render of a LivePage and the JavaScript required
  687.     for the client to communicate asynchronously with the server.
  688.  
  689.     A LivePage grants the client browser the capability of calling server-side
  690.     Python methods using a small amount of JavaScript code. There are two
  691.     types of Python handler methods, persistent handlers and transient handlers.
  692.  
  693.     1) To grant the client the capability to call a persistent handler over and over
  694.         as many times as it wishes, subclass LivePage and provide handle_foo
  695.         methods. The client can then call handle_foo by executing the following
  696.         JavaScript:
  697.  
  698.           server.handle('foo')
  699.  
  700.         handle_foo will be invoked because the default implementation of
  701.         locateHandler looks for a method prefixed handle_*. To change this,
  702.         override locateHandler to do what you wish.
  703.  
  704.     2) To grant the client the capability of calling a handler once and
  705.         exactly once, use ClientHandle.transient to register a callable and
  706.         embed the return result in a page to render JavaScript which will
  707.         invoke the transient handler when executed. For example:
  708.  
  709.         def render_clickable(self, ctx, data):
  710.             def hello(ctx):
  711.                 return livepage.alert(\"Hello, world. You can only click me once.\")
  712.  
  713.             return ctx.tag(onclick=IClientHandle(ctx).transient(hello))
  714.  
  715.         The return result of transient can also be called to pass additional
  716.         arguments to the transient handler. For example:
  717.  
  718.         def render_choice(self, ctx, data):
  719.             def chosen(ctx, choseWhat):
  720.                 return livepage.set(
  721.                     \"choosable\",
  722.                     [\"Thanks for choosing \", choseWhat])
  723.  
  724.             chooser = IClientHandle(ctx).transient(chosen)
  725.  
  726.             return span(id=\"choosable\")[
  727.                 \"Choose one:\",
  728.                 p(onclick=chooser(\"one\"))[\"One\"],
  729.                 p(onclick=chooser(\"two\"))[\"Two\"]]
  730.  
  731.         Note that the above situation displays temporary UI to the
  732.         user. When the user invokes the chosen handler, the UI which
  733.         allowed the user to invoke the chosen handler is removed from
  734.         the client. Thus, it is important that the transient registration
  735.         is deleted once it is invoked, otherwise uncollectable garbage
  736.         would accumulate in the handler dictionary. It is also important
  737.         that either the one or the two button consume the same handler,
  738.         since it is an either/or choice. If two handlers were registered,
  739.         the untaken choice would be uncollectable garbage.
  740.     """
  741.     refreshInterval = 30
  742.     targetTimeoutCount = 3
  743.  
  744.     clientFactory = theDefaultClientHandleFactory
  745.  
  746.     def renderHTTP(self, ctx):
  747.         if not self.cacheable:
  748.             neverEverCache(inevow.IRequest(ctx))
  749.         return rend.Page.renderHTTP(self, ctx)
  750.  
  751.     def locateHandler(self, ctx, path, name):
  752.         ### XXX TODO: Handle path
  753.         return getattr(self, 'handle_%s' % (name, ))
  754.  
  755.     def goingLive(self, ctx, handle):
  756.         """This particular LivePage instance is 'going live' from the
  757.         perspective of the ClientHandle 'handle'. Override this to
  758.         get notified when a new browser window observes this page.
  759.  
  760.         This means that a new user is now looking at the page, an old
  761.         user has refreshed the page, or an old user has opened a new
  762.         window or tab onto the page.
  763.  
  764.         This is the first time the ClientHandle instance is available
  765.         for general use by the server. This Page may wish to keep
  766.         track of the ClientHandle instances depending on how your
  767.         application is set up.
  768.         """
  769.         pass
  770.  
  771.     def child_livepage_client(self, ctx):
  772.         return theDefaultClientHandlesResource
  773.  
  774.     # child_nevow_glue.js = static.File # see below
  775.  
  776.     def render_liveid(self, ctx, data):
  777.         warnings.warn("You don't need a liveid renderer any more; just liveglue is fine.",
  778.                       DeprecationWarning)
  779.         return ''
  780.  
  781.     cacheable = False           # Set this to true to use ***HIGHLY***
  782.                                 # EXPERIMENTAL lazy ID allocation feature,
  783.                                 # which will allow your LivePage instances to
  784.                                 # be cached by clients.
  785.  
  786.     def render_liveglue(self, ctx, data):
  787.         if not self.cacheable:
  788.             handleId = "'", self.clientFactory.newClientHandle(
  789.                 self,
  790.                 self.refreshInterval,
  791.                 self.targetTimeoutCount).handleId, "'"
  792.         else:
  793.             handleId = 'null'
  794.  
  795.         return [
  796.             tags.script(type="text/javascript")[
  797.                 "var nevow_clientHandleId = ", handleId ,";"],
  798.             tags.script(type="text/javascript",
  799.                         src=url.here.child('nevow_glue.js'))
  800.             ]
  801.  
  802.  
  803. setattr(
  804.     LivePage,
  805.     'child_nevow_glue.js',
  806.     static.File(
  807.         util.resource_filename('nevow', 'liveglue.js'),
  808.         'text/javascript'))
  809.  
  810.  
  811. glue = tags.directive('liveglue')
  812.  
  813.  
  814.  
  815.  
  816. ##### BACKWARDS COMPATIBILITY CODE
  817.  
  818.  
  819. ctsTemplate = "nevow_clientToServerEvent('%s',this,''%s)%s"
  820. handledEventPostlude = '; return false;'
  821.  
  822.  
  823. class handler(object):
  824.     callme = None
  825.     args = ()
  826.     identifier = None
  827.     def __init__(self, *args, **kw):
  828.         """**DEPRECATED** [0.5]
  829.  
  830.         Handler is now deprecated. To expose server-side code to the client
  831.         to be called by JavaScript, read the LivePage docstring.
  832.         """
  833.         warnings.warn(
  834.             "[0.5] livepage.handler is deprecated; Provide handle_foo methods (or override locateHandler) on your LivePage and use (in javascript) server.handle('foo'), or use ClientHandle.transient to register a one-shot handler capability.",
  835.             DeprecationWarning,
  836.             2)
  837.         ## Handle working like a 2.4 decorator where calling handler returns a decorator
  838.         if not callable(args[0]) or isinstance(args[0], _js):
  839.             self.args = args
  840.             return
  841.         self.callme = args[0]
  842.         self(*args[1:], **kw)
  843.  
  844.     def __call__(self, *args, **kw):
  845.         if self.callme is None:
  846.             self.callme = args[0]
  847.             args = args[1:]
  848.  
  849.         self.args += args
  850.         self.outsideAttribute = kw.get('outsideAttribute')
  851.         bubble = kw.get('bubble')
  852.         if bubble:
  853.             self.postlude = ';'
  854.         else:
  855.             self.postlude = handledEventPostlude
  856.  
  857.         if 'identifier' in kw:
  858.             self.identifier = kw['identifier']
  859.  
  860.         return self
  861.  
  862.     content = property(lambda self: flt(self))
  863.  
  864.  
  865. def flattenHandler(handler, ctx):
  866.     client = IClientHandle(ctx)
  867.     iden = handler.identifier
  868.     if iden is None:
  869.         iden = client.nextId()
  870.     iden = '--handler-%s' % (iden, )
  871.     ## TODO this should be the IHandlerFactory instead of IResource
  872.     setattr(IHandlerFactory(ctx), 'handle_%s' % (iden, ), handler.callme)
  873.     isAttrib = not handler.outsideAttribute
  874.     new = JavascriptContext(ctx, tags.invisible[handler.args], isAttrib=isAttrib)
  875.  
  876.     rv = flat.flatten(
  877.         js.nevow_clientToServerEvent(*(iden, this, '') + handler.args),
  878.         new)
  879.     rv += handler.postlude
  880.     return tags.xml(rv)
  881. flat.registerFlattener(flattenHandler, handler)
  882.  
  883.  
  884. def flt(stan, quote=True, client=None, handlerFactory=None):
  885.     """Flatten some stan to a string suitable for embedding in a javascript
  886.     string.
  887.  
  888.     If quote is True, apostrophe, quote, and newline will be quoted
  889.     """
  890.     warnings.warn("[0.5] livepage.flt is deprecated. Don't use it.", DeprecationWarning, 2)
  891.     from nevow import testutil
  892.     fr = testutil.FakeRequest()
  893.     ctx = context.RequestContext(tag=fr)
  894.     ctx.remember(client, IClientHandle)
  895.     ctx.remember(handlerFactory, IHandlerFactory)
  896.     ctx.remember(None, inevow.IData)
  897.  
  898.     fl = flat.flatten(stan, ctx=ctx)
  899.     if quote:
  900.         fl = fl.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  901.     return fl
  902.